package com.dandev.cmdemo.web;

import java.text.SimpleDateFormat;
import java.util.Date;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.dandev.cmdemo.form.Communique;
import com.dandev.cmdemo.form.Contact;
import com.dandev.cmdemo.service.ContactService;

/**
 * This handles the edit of a single communique
 * 
 * @author Dan
 */
@Controller
@RequestMapping("/editcomm")
public class CommItemController {
	
	@Autowired
    private ContactService contactService;
	
	/**
	 * Custom binder config, used for date formating.
	 * @param dataBinder
	 */
	@InitBinder
	public void initBinder(WebDataBinder dataBinder) {
	 
	SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yyyy h:m a");
	sdf.setLenient(false);
	dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
	
	}
	
	/**
	 * Prepare for communique edit
	 * @param commId of communique to edit
	 * @param model
	 */
	@RequestMapping(method=RequestMethod.GET)
	public void getForm(@RequestParam(value = "commId") Long commId, Model model) {
		
		Communique comm = contactService.getCommunique(commId);
		
		model.addAttribute("comm", comm);
		
	}
	
	/**
	 * Handle edit post.
	 * @param comm form data
	 * @param result of validation
	 * @param model
	 * @return view name
	 */
	@RequestMapping(method=RequestMethod.POST)
	public String postEdit(@ModelAttribute("comm") @Valid Communique comm,  BindingResult result, Model model) {
		
		if (result.hasErrors()) {
			System.out.println(result.toString());
			return "editcomm";
		}
		
		
		contactService.addCommunique(comm);
		
		return "redirect:/comm?contactId=" + comm.getParentContactId();
	}
	
}
